package com.ztjava.core.util;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateUtil {
	public static final String HOUR = "HOUR";
	public static final String DAY = "DAY";
	public static final String WEEK = "WEEK";
	public static final String MONTH = "MONTH";
	public static final String YEAR = "YEAR";
	public static final String MINUTE = "MINUTE";
	public static final String SECOND = "SECOND";
	/**
	 * 日期加减
	 * @param date
	 * @param type
	 * @param nu
	 * @return
	 */
	public static Date dateAdd(Date date,String type,Integer nu) {
		if(date==null) date = new Date(); 
		GregorianCalendar gc = new GregorianCalendar(); 
		gc.setTime(date);
		if(type.equals("HOUR")) {
			gc.add(Calendar.HOUR_OF_DAY, nu);
		}else if(type.equals("DAY")) {
			gc.add(Calendar.DAY_OF_MONTH, nu);
		}else if(type.equals("WEEK")){
			gc.add(Calendar.WEEK_OF_YEAR,nu);
		}else if(type.equals("MONTH")) {
			gc.add(Calendar.MONTH, nu);
		}else if(type.equals("YEAR")) {
			gc.add(Calendar.YEAR,nu);
		}else if(type.equals("MINUTE")) {
			gc.add(Calendar.MINUTE,nu);
		}else if(type.equals("SECOND")) {
			gc.add(Calendar.SECOND,nu);
		}
		return gc.getTime();
	}
	
	public static String dataAddFormat(Date date,String type,Integer nu) {
		return DateUtil.dataAddFormat(date, type, nu,"yyyy-MM-dd HH:mm:ss");
	}
	public static String dataAddFormat(Date date,String type,Integer nu,String format) {
		return DateUtil.formatDateToStr(format, dateAdd(date, type, nu));
	}
	/**
	 * 日期转字符串
	 * @param format
	 * @param date
	 * @return
	 */
	public static String formatDateToStr(String format,Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		if(date==null) {
			date = new Date();
		}
		return sdf.format(date);
	}
	/**
	 * 获取当前日期字符串
	 * @return
	 */
	public static String timeFormat = "yyyy-MM-dd HH:mm:ss";
	public static String getNowTime() {
		return formatDateToStr(timeFormat, new Date());
	}
	public static Timestamp getNowTimestamp(){
		return  new Timestamp(System.currentTimeMillis()); 
	}
	/**
	 * 字符串转日期
	 */
	public static Date formStrToDate(String format,String date){
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date result = null;
		try {
			result = sdf.parse(date);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
